// +----------------------------------------------------------------------
// | ShopSuite商城系统 [ 赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | 版权所有 随商信息技术（上海）有限公司
// +----------------------------------------------------------------------
// | 未获商业授权前，不得将本软件用于商业用途。禁止整体或任何部分基础上以发展任何派生版本、
// | 修改版本或第三方版本用于重新分发。
// +----------------------------------------------------------------------
// | 官方网站: https://www.shopsuite.cn  https://www.modulithshop.cn
// +----------------------------------------------------------------------
// | 版权和免责声明:
// | 本公司对该软件产品拥有知识产权（包括但不限于商标权、专利权、著作权、商业秘密等）
// | 均受到相关法律法规的保护，任何个人、组织和单位不得在未经本团队书面授权的情况下对所授权
// | 软件框架产品本身申请相关的知识产权，禁止用于任何违法、侵害他人合法权益等恶意的行为，禁
// | 止用于任何违反我国法律法规的一切项目研发，任何个人、组织和单位用于项目研发而产生的任何
// | 意外、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、
// | 附带或衍生的损失等)，本团队不承担任何法律责任，本软件框架只能用于公司和个人内部的
// | 法律所允许的合法合规的软件产品研发，详细见https://www.modulithshop.cn/policy
// +----------------------------------------------------------------------
package com.suisung.shopsuite.trade.repository.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.suisung.shopsuite.common.utils.TimeRange;
import com.suisung.shopsuite.common.utils.TimeUtil;
import com.suisung.shopsuite.core.web.repository.impl.BaseRepositoryImpl;
import com.suisung.shopsuite.trade.dao.DistributionOrderDao;
import com.suisung.shopsuite.trade.model.entity.DistributionOrder;
import com.suisung.shopsuite.trade.repository.DistributionOrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.suisung.shopsuite.common.utils.I18nUtil.__;


/**
 * <p>
 * 推广订单收益详情表 服务实现类
 * </p>
 *
 * @author Xinze
 * @since 2021-09-11
 */
@Repository
public class DistributionOrderRepositoryImpl extends BaseRepositoryImpl<DistributionOrderDao, DistributionOrder> implements DistributionOrderRepository {

    @Autowired
    private DistributionOrderDao distributionOrderDao;


    @Override
    public float calCommission(Integer userId, Integer uoLevel, Long startTime, Long endTime) {
        return ObjectUtil.defaultIfNull(distributionOrderDao.getBuyCommissionTotal(userId, uoLevel, startTime, endTime, null, true), 0f);
    }


    /**
     * 订单数量
     *
     * @param userId
     * @param month_flag
     */
    @Override
    public long getOrderNum(Integer userId, Boolean month_flag) {
        QueryWrapper<DistributionOrder> queryWrapper = new QueryWrapper<>();

        if (userId != null) {
            queryWrapper.eq("user_id", userId);
        }

        if (month_flag != null && month_flag) {
            queryWrapper.gt("uo_time", DateUtil.beginOfMonth(new Date()).getTime());
        }

        return count(queryWrapper);
    }

    @Override
    public Map getCommissionTimeline(int days, Integer userId, boolean is_assoc) {

        TimeRange timeRange = TimeUtil.lastNDays(days);

        List<Map> order_num_rows = distributionOrderDao.getCommissionTimeline(userId, timeRange.getStart(), timeRange.getEnd());

        Map timeline_rows = formatTimeline(order_num_rows, timeRange.getStart(), timeRange.getEnd(), is_assoc);

        return timeline_rows;
    }

    @Override
    public Map formatTimeline(List<Map> order_num_rows, Long start_time, Long end_time, boolean is_assoc) {
        Map timeline_rows = new HashMap();
        List<Map> timeline_row_list = new ArrayList();

        for (Map order_num_row : order_num_rows) {

            String year = Convert.toStr(order_num_row.get("year"));
            String month = Convert.toStr(order_num_row.get("month"));
            String day = Convert.toStr(order_num_row.get("day"));
            String concat = year.concat("_").concat(month);
            String key = concat.concat("_").concat(day);
            timeline_rows.put(key, order_num_row);

        }

        for (Long toLongstart_time = start_time; toLongstart_time <= end_time; toLongstart_time += Convert.toLong(60 * 60 * 24 * 1000)) {
            Map keys = new HashMap();
            Date date = Convert.toDate(toLongstart_time);
            Integer month = DateUtil.month(date) + 1;
            DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd");
            String key = dateFormat.format(date);
            int year = DateUtil.year(date);
            int day = DateUtil.dayOfMonth(date);
            if (ObjectUtil.isNull(timeline_rows.get(key))) {
                keys.put("num", 0);
                keys.put("amount", 0);
                keys.put("time", Convert.toStr(month).concat("/").concat(Convert.toStr(day)));
                keys.put("year", year);
                keys.put("month", month);
                keys.put("day", day);
                timeline_rows.put(key, keys);
            } else {
                keys = (Map) timeline_rows.get(key);
                keys.put("time", Convert.toStr(month).concat("/").concat(Convert.toStr(day)));
            }

            timeline_row_list.add(keys);
        }

        List<String> categories = timeline_row_list.stream().map(s -> Convert.toStr(s.get("time"), "")).distinct()
                .collect(Collectors.toList());
        timeline_rows.put("categories", categories);
        List<BigDecimal> data = timeline_row_list.stream().map(s -> Convert.toBigDecimal(s.get("amount"))).collect(Collectors.toList());

        List<Map> series = new ArrayList<>();
        Map map = new HashMap();
        map.put("data", data);
        map.put("name", __("最近佣金"));
        series.add(map);
        timeline_rows.put("series", series);

        return timeline_rows;
    }
}
